package com.feizhoutuobang.shapeline.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;

import com.feizhoutuobang.shapeline.bo.Delivery;
import com.feizhoutuobang.shapeline.dao.DeliveryDao;
import com.feizhoutuobang.shapeline.service.ConfigService;
import com.feizhoutuobang.shapeline.service.DeliverService;
import com.feizhoutuobang.shapeline.util.Calendar;
import com.feizhoutuobang.shapeline.util.mail.SendMail;

public class DeliverServiceImpl implements DeliverService {

	private static final Logger LOG = Logger.getLogger(DeliverServiceImpl.class);
	
	private DeliveryDao deliveryDao;
	private ConfigService configService;
	
	public DeliveryDao getDeliveryDao() {
		return deliveryDao;
	}

	public void setDeliveryDao(DeliveryDao deliveryDao) {
		this.deliveryDao = deliveryDao;
	}

	public ConfigService getConfigService() {
		return configService;
	}

	public void setConfigService(ConfigService configService) {
		this.configService = configService;
	}

	@Override
	public void deliverSubscription() {
		List<Delivery> deliveries = getDeliveryDao().getTodoDeliveries();
		
		for (Delivery delivery : deliveries) {
			LOG.info("find delivery, file: " + delivery.getFilePath() + ", to: " + delivery.getDeliverEmail());
			try {
		        SendMail sm = new SendMail();
		        sm.setMessageBasePath("");
		        
		        sm.setSMTPHost(getConfigService().getStringValue("mail.host"));
		        sm.setMailFrom(getConfigService().getStringValue("mail.reply"));
		        sm.setMailAccount(getConfigService().getStringValue("mail.account"));
		        sm.setMailPass(getConfigService().getStringValue("mail.password"));
		        
		        sm.setMailTo(delivery.getDeliverEmail());
		        List<String> filelist = new ArrayList<String>();
		        filelist.add(delivery.getFilePath());
		        sm.setAttachedFileList(filelist);
		        sm.setMsgContent(delivery.getFileName());
		        sm.setSubject(delivery.getFileName());
		        sm.sendMail();
		        
		        delivery.setDone(true);
		        delivery.setDeliverTime(Calendar.now());
		        delivery.setSuccessful(true);
			}
			catch (Exception e) {
				LOG.error("error when send mail", e);
				
				delivery.setDone(true);
				delivery.setSuccessful(false);
				delivery.setMessage(e.getMessage());
			}
			
			try {
				getDeliveryDao().updateDelivery(delivery);
			}
			catch (Exception e) {
				LOG.error("error when update delivery", e);
			}
		}
		
	}

}
